package com.milk_shop.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.opensymphony.xwork2.ActionContext;

import java.util.Map;
import java.util.Random;

import org.apache.commons.collections4.map.HashedMap;

/**
 * 短信发送工具类
 */
public class SendSmsUtil {
    /**
     * 发送短信
     */
    public static void SendSms(String phoneNumber) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GEHwtGiyrjShmT8PJtD", "xJUi5SWn0gBZeB9vrSvMfvzzHNPK48");
        IAcsClient client = new DefaultAcsClient(profile);
        String captcha = generateCaptcha(6);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", "四季奶坊");
        request.putQueryParameter("TemplateCode", "SMS_205893417");
        request.putQueryParameter("TemplateParam", "{\"code\": "+ captcha +"}");
        ActionContext.getContext().put(phoneNumber, captcha);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成验证码
     * @param length 验证码长度
     */
    private static String generateCaptcha(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(6));
        }
        return sb.toString();
    }

}
